package com.my.code.concurrent;

import java.util.concurrent.atomic.AtomicStampedReference;

public class TestAtomicStampedReference {
    private static AtomicStampedReference<Integer> asr = new AtomicStampedReference<>(1, 0);

    public static void main(String[] args) {
        Thread other = new Thread(() -> {
            asr.compareAndSet(1, 2, asr.getStamp(), asr.getStamp() + 1);
            System.out.println(Thread.currentThread() + ",【increment】 ,v=" + asr.getReference() + ", stamp=" + asr.getStamp());

            asr.compareAndSet(2, 1, asr.getStamp(), asr.getStamp() + 1);
            System.out.println(Thread.currentThread() + ",【decrement】 ,v=" + asr.getReference() + ", stamp=" + asr.getStamp());
        }, "other");//干扰线程

        Thread first = new Thread(() -> {
            int v = asr.getReference();
            int stamp = asr.getStamp(); //获取当前标识
            System.out.println(Thread.currentThread() + ", v= " + v + " ,stamp=" + stamp);//v可能为1也可能为2
            try {
                other.join();
                //Thread.sleep(1000); //等待1秒 ，以便让干扰线程执行
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            //此时expectedReference未发生改变，但是stamp已经被修改了,所以CAS失败
            boolean isCASSuccess = asr.compareAndSet(1, 2, stamp, stamp + 1);
            System.out.println(Thread.currentThread() + ", v=" + asr.getReference() + ", stamp=" + asr.getStamp() + ", CAS操作结果: " + isCASSuccess);
        }, "first");//主线程

        first.start();
        other.start();
    }
}
